<template>
  <div class="box">
    <div class="searcharea">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="24">
          <div class="query">
            <el-form :inline="true" :model="queryMaterialParam" class="demo-form-inline">
              <el-form-item label="原料名称">
                <el-input
                  v-model="queryMaterialParam.MaterialName"
                  placeholder="请输入"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :icon="Search" @click="SearchMaterial()">搜索</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="contentarea">
      <!-- 功能按钮 -->
      <el-row>
        <el-col :span="24">
          <div class="functionbutton">
            <el-button type="primary" plain @click="addMaterial()">添加</el-button>
            <el-button type="danger" plain @click="batchDeletionMaterial()">批量删除</el-button>
          </div>
        </el-col>
        <el-dialog
          v-model="centerDialogVisible"
          title="添加原料"
          width="30%"
          align-center
          :before-close="CreateMaterialhandleClose"
        >
          <el-form
            ref="CreateMaterialFormRef"
            :model="CreateMaterialForm"
            :rules="CreateMaterialRules"
            label-width="auto"
            style="padding: 20px"
          >
            <el-form-item label="原料编号" prop="MaterialsCode">
              <el-input v-model="CreateMaterialForm.MaterialsCode" placeholder="不输入则自动生成"> </el-input>
            </el-form-item>
            <el-form-item prop="MaterialsName" label="原料名称">
              <el-input v-model="CreateMaterialForm.MaterialsName" placeholder="请输入原料名称"> </el-input>
            </el-form-item>
            <el-form-item prop="ModelNumber" label="型号">
              <el-input v-model="CreateMaterialForm.ModelNumber" placeholder="请输入原料名称"> </el-input>
            </el-form-item>
            <el-form-item prop="Specification" label="规格">
              <el-input v-model="CreateMaterialForm.Specification" placeholder="请输入原料名称"> </el-input>
            </el-form-item>
            <el-form-item prop="Supplier" label="供应商">
              <el-input v-model="CreateMaterialForm.Supplier" placeholder="请输入原料名称"> </el-input>
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="CreateMaterialhandleClose">取消</el-button>
              <el-button type="primary" @click="CreateMaterialDialog(CreateMaterialFormRef)">确认</el-button>
            </div>
          </template>
        </el-dialog>
      </el-row>

      <!-- 数据表格 -->
      <el-row>
        <el-col :span="24">
          <div>
            <el-table
              v-loading="tableloading"
              :data="tableData"
              border
              style="width: 100%"
              max-height="400px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              row-key="id"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="80" />
              <el-table-column prop="materialsCode" label="原料编码" width="180" />
              <el-table-column prop="materialsName" label="原料名称" width="180" />
              <el-table-column prop="modelNumber" label="型号" width="180" />
              <el-table-column prop="specification" label="规格" width="180" />
              <el-table-column prop="supplier" label="供应商" width="180" />
              <el-table-column prop="creator" label="创建人" />
              <el-table-column prop="updator" label="修改人" />
              <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
              <el-table-column fixed="right" label="操作" width="140">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteMaterialSingle(scope.row.id)">
                    删除
                  </el-button>

                  <el-button type="primary" plain size="small" @click="UpdateMaterial(scope.row)">更新</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>

        <el-dialog v-model="UpdateDialogVisible" title="修改原料" width="30%" align-center>
          <el-form
            ref="UpdateMaterialFormRef"
            :model="UpdateMaterialForm"
            :rules="CreateMaterialRules"
            label-width="auto"
            style="padding: 20px"
          >
            <el-form-item label="原料编号">
              <el-input v-model="UpdateMaterialForm.MaterialsCode" disabled placeholder="不输入则自动生成"> </el-input>
            </el-form-item>
            <el-form-item prop="MaterialsName" label="原料名称">
              <el-input v-model="UpdateMaterialForm.MaterialsName" placeholder="请输入原料名称"> </el-input>
            </el-form-item>
            <el-form-item prop="ModelNumber" label="型号">
              <el-input v-model="UpdateMaterialForm.ModelNumber" placeholder="请输入原料名称"> </el-input>
            </el-form-item>
            <el-form-item prop="Specification" label="规格">
              <el-input v-model="UpdateMaterialForm.Specification" placeholder="请输入原料名称"> </el-input>
            </el-form-item>
            <el-form-item prop="Supplier" label="供应商">
              <el-input v-model="UpdateMaterialForm.Supplier" placeholder="请输入原料名称"> </el-input>
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="UpdateDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="UpdateMaterialDialog(UpdateMaterialFormRef)">确认</el-button>
            </div>
          </template>
        </el-dialog>
      </el-row>

      <!-- 分页 -->
      <el-row>
        <el-col :span="24">
          <div class="demo-pagination-block" style="display: flex; justify-content: flex-end">
            <el-config-provider :locale="zhCn">
              <el-pagination
                v-model:current-page="queryMaterialParam.PageIndex"
                v-model:page-size="queryMaterialParam.PageSize"
                :page-sizes="[100, 200, 300, 400]"
                :small="false"
                :disabled="false"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryMaterialParam.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </el-config-provider>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessageBox, ElNotification, FormInstance } from 'element-plus'
import {
  ApiGetProductPlanning_MaterialPageListAsync,
  ApiDeletionProductPlanning_MaterialAsync,
  ApiCreateProductPlanning_MaterialAsync,
  ApiUpdateProductPlanning_MaterialAsync
} from '../../api/productPlanning/ProductPlanningMaterialApi'
import { formatTime, capitalizeFirstLetter } from '../../utils/index'

// 定义接口和类型
interface MaterialParam {
  MaterialsName: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
}

interface Material {
  id: string
}

// 响应式变量
const tableloading = ref(false)
const UpdateDialogVisible = ref(false)
const centerDialogVisible = ref(false)
const selectedRows = ref<string[]>([]) // 存储选中的行数据
const CreateMaterialFormRef = ref<FormInstance>()

// 表单数据和验证规则
const CreateMaterialForm: Material = reactive({ id: '' })
const UpdateMaterialForm: Material = reactive({ id: '' })
const CreateMaterialRules = reactive({
  MaterialsName: [{ required: true, message: '原料名称不能为空', trigger: 'blur' }]
})

// 查询参数
const queryMaterialParam: MaterialParam = reactive({
  MaterialsName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 表格数据
const tableData = ref([])

// 搜索原料
const SearchMaterial = () => {
  tableloading.value = true
  ApiGetProductPlanning_MaterialPageListAsync(queryMaterialParam)
    .then((res) => {
      tableData.value = res.data.data
      queryMaterialParam.PageIndex = res.data.pageIndex
      queryMaterialParam.PageSize = res.data.pageSize
      queryMaterialParam.totalCount = res.data.totalCount
    })
    .finally(() => {
      tableloading.value = false
    })
}

// 关闭创建原料对话框
const CreateMaterialhandleClose = () => {
  const formEl = CreateMaterialFormRef.value
  if (!formEl) return
  formEl.resetFields()
  centerDialogVisible.value = false
}

// 打开添加原料对话框
const addMaterial = () => {
  centerDialogVisible.value = true
}

// 确认添加原料
const CreateMaterialDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ApiCreateProductPlanning_MaterialAsync(CreateMaterialForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '创建成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          CreateMaterialhandleClose()
          SearchMaterial()
        }
      })
    }
  })
}

// 打开更新原料信息对话框
const UpdateMaterial = (row: { [key: string]: string | number }) => {
  Object.assign(UpdateMaterialForm, capitalizeFirstLetter(row))
  UpdateDialogVisible.value = true
}

// 确认更新原料信息
const UpdateMaterialFormRef = ref<FormInstance>()
const UpdateMaterialDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ApiUpdateProductPlanning_MaterialAsync(UpdateMaterialForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '更新成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          UpdateDialogVisible.value = false
          SearchMaterial()
        }
      })
    }
  })
}

// 删除单个原料
const DeleteMaterialSingle = (id: string) => {
  selectedRows.value = [id]
  batchDeletionMaterial()
}

// 批量删除原料
const batchDeletionMaterial = () => {
  if (selectedRows.value.length < 1) {
    ElNotification({
      message: '请先选择一条或更多信息',
      type: 'warning',
      offset: 100,
      duration: 2000
    })
    return
  }
  ElMessageBox.confirm('确实要删除这些信息吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ApiDeletionProductPlanning_MaterialAsync(selectedRows.value)
        .then((res) => {
          if (res.data.data) {
            ElNotification({
              message: '删除成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
            selectedRows.value = []
            SearchMaterial()
          }
        })
        .catch(() => {
          selectedRows.value = []
        })
    })
    .catch(() => {
      selectedRows.value = []
    })
}

// 获取用户选择项
const handleSelectionChange = (val: Material[]) => {
  selectedRows.value = val.map((item) => item.id)
}

// 时间转换
const formatColumnTime = (row: object, column: string, time: string | number | Date) => {
  if (time === null) {
    return ''
  }

  if (typeof time === 'string' || typeof time === 'number') {
    return formatTime(time)
  } else {
    return formatTime(time.getTime())
  }
}

// 每页条数
const handleSizeChange = (e: number) => {
  queryMaterialParam.PageSize = e
  SearchMaterial()
}

// 当前页变化
const handleCurrentChange = (e: number) => {
  queryMaterialParam.PageIndex = e
  SearchMaterial()
}

// 初次加载数据
onMounted(() => {
  SearchMaterial()
})
</script>



<style lang="less"  scoped>
@import '../../assets/globle/index.css';
</style>
